$(function () {
  guanxitu = 1;
  initguanxituData();

})

//动态累加参数
const currYear = localStorage.getItem("year");
const currMon = localStorage.getItem("month");
const currDept = localStorage.getItem("dept");
const username = localStorage.getItem("user");
const budgetNo = localStorage.getItem("budgetNo");
const budgetName = localStorage.getItem("budgetName");
console.log(budgetName)
let newObj = {
  username: username,
  budgetYear: currYear,
  budgetMonth: currMon,
  dept: currDept,
  status: 2,
  chartPage: 70401,
  chartNo: 5,
  budgetNo: budgetNo,
  // budgetNo: "000100010001",
  key01: '',
  key02: '',
  key03: '',
  nodeDept: '',
  seq01: '',
  seq02: '',
  seq03: '',
  seq04: '',
};

//请求数据
function initguanxituData() {
  //加载ing
  // document.getElementById("loadingText").style.display = "block";
  //请求数据
  let obj = newObj
  ApiGet("getdata", obj, function (e) {
    var json = JSON.parse(e);
    // console.log(json)
    var chartData = json.items[0].charts[0].data;
    let firstobj = {
      key01: '',
      key02: '',
      key03: '',
      key04: '',
      key05: budgetName,
      key06: "000",
      key07: '0',
    }
    chartData.unshift(firstobj)
    console.log(chartData)

    let jsonData = []
    chartData.map(item => {
      let obj = {
        key01: item.key01,
        key02: item.key02,
        key03: item.key03,
        key04: item.key04,
        name: item.key05,
        id: item.key06,
        pid: item.key07 ? item.key07 : "000",
        key011: item.key08,
        key022: item.key09,
        key033: item.key10,
        seq01: item.key12,
        seq02: item.key13,
        seq03: item.key14,
        seq04: item.key15,
      }
      jsonData.push(obj)
    })
    console.log(jsonData)

    const transData = (jsonArr, idStr, pidStr, childrenStr) => {
      // console.log(jsonArr)
      // 存放的最终结果树数组
      const result = [];
      const id = idStr;
      const pid = pidStr;
      const children = childrenStr;
      const len = jsonArr.length;
      // 遍历得到以id为键名的对象(建立整棵树的索引)
      const hash = {};
      jsonArr.forEach(item => {
        hash[item[id]] = item;
      });
      for (let j = 0; j < len; j++) {
        const jsonArrItem = jsonArr[j];
        const hashItem = hash[jsonArrItem[pid]];
        if (hashItem) {
          // 如果当前项还没有children属性，则添加该属性并设置为空数组
          !hashItem[children] && (hashItem[children] = []);
          hashItem[children].push(jsonArrItem);
        } else {
          result.push(jsonArrItem);
        }
      }
      return result;
    };
    const jsonDataTree = transData(jsonData, 'id', 'pid', 'children');
    console.log(jsonDataTree);
    guanxituChart(jsonDataTree);
  });
}
$(window).on('click', function () {
  $(myChart).resize();
})
var myChart = echarts.init(document.getElementById("gaunxitu"));
var colors = [
  "#20C997",
  "#FD9843",
  "#8C68CD",
  "#E35D6A",
  "#FFC107",
  "#FD7E14",
  "#DC3545",
  "#95F300",
  "#D63384",
  "#6F42C1"
]

function guanxituChart(jsonDataTree) {
  var getdata = function getData() {
    let data = jsonDataTree[0]

    let arr = []
    arr.push(data)
    arr = handle(arr, 0)
    return arr;
  }
  var handle = function handleData(data, index, color = '#00f6ff') {
    //index标识第几层
    return data.map((item, index2) => {
      // console.log(item)
      //计算出颜色
      if (index == 1) {
        color = colors.find((item, eq) => eq == index2 % 10);
      }
      // 设置节点大小
      if (index === 0 || index === 1) {
        item.label = {
          position: "inside",
          rotate: 0,
          borderRadius: "50%",
        }
      } else {
        item.label = { //标签样式
          color: "#4E5969",
          fontSize: 12,
          fontFamily: "SourceHanSansCN",
          position: "inside",
          rotate: 0,
        }
      }
      // 设置label大小
      switch (index) {
        case 0:
          item.symbolSize = 120
          break;
        case 1:
          item.symbolSize = 90
          break;
        default:
          item.symbolSize = 60
          break;
      }
      // 设置线条颜色
      item.lineStyle = {
        color: color
      }

      if (item.children) { //存在子节点
        item.itemStyle = {
          borderColor: color,
          color: color
        };
        item.children = handle(item.children, index + 1, color)
      } else { //不存在
        item.itemStyle = {
          color: 'transparent',
          borderColor: color
        };
      }
      return item
    })
  }
  var option = {
    type: "tree",
    backgroundColor: "#FFf",
    toolbox: { //工具栏
      show: true,
      iconStyle: {
        borderColor: "#03ceda"
      },
      feature: {
        restore: {}
      }
    },
    tooltip: { //提示框
      trigger: "item",
      triggerOn: "mousemove",
      textStyle: {
        fontSize: 12
      },
      formatter: function (params) {
        if (params.data.key01 || params.data.key02 || params.data.key03) {
          let str = `
        <p style="font-weight: 600;">${params.data.name}</p>   </br>
        <span style="margin-right:10px">预算金额 :</span> 
        <span>${((params.data.key01)/10000).toFixed(2)}</span> 万元 </br>
        <span style="margin-right:10px">执行金额 :</span> 
        <span>${((params.data.key02)/10000).toFixed(2)}</span> 万元 </br>
        <span style="margin-right:10px">剩余金额 :</span> 
        <span>${ ((params.data.key03)/10000).toFixed(2)}</span> 万元 </br>
        <span style="margin-right:10px">执行率 :</span>
        <span>${ ((params.data.key04) * 100).toFixed(1)}</span> % </br>`
          return str;
        }
      },
    },
    series: [{
      type: "tree",
      hoverAnimation: true, //hover样式
      data: getdata(),
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      layout: "radial",
      symbol: "circle",
      symbolSize: 10,
      nodePadding: 20,
      animationDurationUpdate: 750,
      expandAndCollapse: true, //子树折叠和展开的交互，默认打开
      initialTreeDepth: 10,
      roam: true, //是否开启鼠标缩放和平移漫游。scale/move/true
      focusNodeAdjacency: true,
      itemStyle: {
        borderWidth: 1,
      },
      label: { //标签样式
        color: "#4E5969",
        fontSize: 12,
        fontFamily: "SourceHanSansCN",
        position: "inside",
        rotate: 0,
        normal: {
          show: true,
          fontSize: 14,
          color: '#4E5969',
          textShadowColor: '#E8F3FF',
          textShadowBlur: 2,

          rich: {
            'rate': {
              fontSize: 10,
              align: 'center'
            },
            'name': {
              fontSize: 14,
              lineHeight: 20,
              align: 'center',
              textBorderColor: '#8CCBFF',
              textBorderWidth: 1
            }
          }
        },
      },
      lineStyle: {
        width: 1,
        curveness: 0.5,
      }
    }]
  };
  myChart.setOption(option);


  myChart.off("click");
  myChart.on('click', function (param) {
    console.log(param, '点击的')

    // console.log(param.treeAncestors.length, '点击的层级')
    console.log(param.name, '点击的name/key05')
    dataIndex = param.treeAncestors.length
    clickName = param.name
    // if (dataIndex == 3) {
    //   //第一层级
    //   localStorage.setItem('seq01', clickName ? clickName : '');
    // }
    // if (dataIndex == 4) {
    //   //第二层级
    //   localStorage.setItem('key03', clickName ? clickName : '');
    // }
    // if (dataIndex == 5) {
    //   //第三层级
    //   localStorage.setItem('seq02', clickName ? clickName : '');
    // }
    // if (dataIndex == 6) {
    //   //第四层级
    //   localStorage.setItem('key01', clickName ? clickName : '');
    // }

    let obj = {
      username: username,
      budgetYear: currYear,
      budgetMonth: currMon,
      dept: currDept,
      status: 2,
      chartPage: 70401,
      chartNo: 5,
      budgetNo: budgetNo,
      // budgetNo: "000100010001",
      key01: param.data.key011,
      key02: param.data.key022,
      key03: param.data.key033,
      nodeDept: param.data.nodeDept,
      seq01: param.data.seq01,
      seq02: param.data.seq02,
      seq03: param.data.seq03,
      seq04: param.data.seq04,
      // key01: localStorage.getItem("key01"),
      // key02: '',
      // key03: localStorage.getItem("key03"),
      // nodeDept: '',
      // seq01: localStorage.getItem("seq01"),
      // seq02: localStorage.getItem("seq02"),
      // seq03: '',
      // seq04: '',
    };
    console.log(obj)
    ApiGet("getdata", obj, function (e) {
      var json = JSON.parse(e);
      var chartData = json.items[0].charts[0].data;
      let firstobj = {
        key01: '',
        key02: '',
        key03: '',
        key04: '',
        key05: budgetName,
        key06: "000",
        key07: '0',
      }
      chartData.unshift(firstobj)
      console.log(chartData)

      let jsonData = []
      chartData.map(item => {
        let obj = {
          key01: item.key01,
          key02: item.key02,
          key03: item.key03,
          key04: item.key04,
          name: item.key05,
          id: item.key06,
          pid: item.key07 ? item.key07 : "000",
          key011: item.key08,
          key022: item.key09,
          key033: item.key10,
          nodeDept: item.key11,
          seq01: item.key12,
          seq02: item.key13,
          seq03: item.key14,
          seq04: item.key15,
        }
        jsonData.push(obj)
      })
      console.log(jsonData)

      const transData = (jsonArr, idStr, pidStr, childrenStr) => {
        console.log(jsonArr)
        // 存放的最终结果树数组
        const result = [];
        const id = idStr;
        const pid = pidStr;
        const children = childrenStr;
        const len = jsonArr.length;
        // 遍历得到以id为键名的对象(建立整棵树的索引)
        const hash = {};
        jsonArr.forEach(item => {
          hash[item[id]] = item;
        });
        for (let j = 0; j < len; j++) {
          const jsonArrItem = jsonArr[j];
          const hashItem = hash[jsonArrItem[pid]];
          if (hashItem) {
            // 如果当前项还没有children属性，则添加该属性并设置为空数组
            !hashItem[children] && (hashItem[children] = []);
            hashItem[children].push(jsonArrItem);
          } else {
            result.push(jsonArrItem);
          }
        }
        return result;
      };
      const jsonDataTree = transData(jsonData, 'id', 'pid', 'children');
      console.log(jsonDataTree);
      guanxituChart(jsonDataTree);

    });
  })


}